#!/usr/bin/python

import sys, os, math, cPickle, stat, time, zlib

class eopen(file):
    def Rread(self, size=-1):
        self.seek(-size, 1)
        data = self.read(size)[::-1]
        self.seek(-size, 1)
        return data
    def Rwrite(self, data):
        c = self.tell()
        self.seek(-len(data), 1)
        n = self.tell()
        if c - n == len(data):
            self.write(data[::-1])
            self.seek(-len(data), 1)
        else:
            return False

if len(sys.argv) > 1:
    if  os.path.exists(sys.argv[1]):
        print "Formatting"
        fp = eopen(sys.argv[1], "rb+")
        fp.seek(0,2)
        end = fp.tell()
        print "Total Bytes: %d"%end
        
        fp.seek(0)
        fp.write("dupFS")
        head=dict()
        meta=dict()
        meta['hashes']=dict()
        meta['path']=dict()
        meta['path']['type']=stat.S_IFDIR
        meta['path']['mode']=0777
        meta['path']['ctime']=int(time.time())
        meta['path']['atime']=int(time.time())
        meta['path']['mtime']=int(time.time())
        meta['path']['uid']=0
        meta['path']['gid']=0
        meta['path']['size']=0
        meta['path']['sub']=dict()
        meta['path']['.trash']=dict()
        meta['path']['.trash']['type']=stat.S_IFDIR
        meta['path']['.trash']['mode']=0777
        meta['path']['.trash']['ctime']=int(time.time())
        meta['path']['.trash']['atime']=int(time.time())
        meta['path']['.trash']['mtime']=int(time.time())
        meta['path']['.trash']['uid']=0
        meta['path']['.trash']['gid']=0
        meta['path']['.trash']['size']=0
        meta['path']['.trash']['sub']=dict()
        meta['lastHash']=""
        meta['lastPos']=512
        Pmeta=cPickle.dumps(meta,2)
        zPmeta=zlib.compress(Pmeta)
        head['totalSize']=end
        head['metaStart']=end - len(zPmeta)
        cPickle.dump(head,fp,2)
        fp.seek(head['metaStart'])
        fp.write(zPmeta)

        
